package org.sensation.file.channel;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;

public class FileReadChannel{
	private String originFilePath;
	private FileChannel originChannel;
	private String fileName;
	private long size;
	private int lastIndex;
	private int remainder;
	private int blockNumber;
	private int blockSize;
	private int offset;
	
	public FileReadChannel(String originFilePath, int blockSize) throws IOException {
		super();
		this.originFilePath = originFilePath;
		initOriginChannel();
		initFileInfo(blockSize);
	}
	
	private void initFileInfo(int blockSize) throws IOException {
		size = originChannel.size();
		this.blockSize = blockSize;
		
		lastIndex = (int) (size / blockSize);
		remainder = (int) (size % blockSize);
		
		blockNumber = lastIndex + remainder;
	}

	private void initOriginChannel() throws IOException {
		File file = new File(originFilePath);
		fileName = file.getName();
		originChannel = new RandomAccessFile(file, "r").getChannel();
	}
	
	public void readFile(int offset, ByteBuffer buffer) throws IOException {		
		buffer.clear();
		originChannel.read(buffer, offset);
	}
	
	public boolean readingBlockSizeFromFile(ByteBuffer buffer) throws IOException{
		if(offset > blockNumber)
			return false;
		
		
		buffer.putInt(offset);
		readFile(offset, buffer);
		
		offset = offset + 1;
		return true;
	}
	
	public long size(){
		return size;
	}
	public String getFileName(){
		return fileName;
	}

	public ByteBuffer createBuffer(){
		return ByteBuffer.allocate(blockSize + 3);
	}
	
	public int getBlockNumber() {
		return blockNumber;
	}

	public void close() throws IOException{
		if(originChannel != null){
			try {
				originChannel.close();
			} catch (Exception e) {
				originChannel.close();
			}
		}
	}
}
